<?php

namespace Base\EventBundle\Repository;

use Doctrine\ORM\EntityRepository;

class EventRepository extends EntityRepository
{
    public function getEvents() {
        $q = $this->createQueryBuilder('e')
             ->addSelect('u.username AS u_username')
             ->addSelect('m.name AS m_name')
             ->innerJoin('e.modification_user_id', 'u')
             ->leftJoin('e.media_id', 'm')
             ->where('e.is_published = 1')
             ->orderBy('e.updatedAt', 'DESC')
             ->getQuery();

        return $q;
    }

    public function getCurrentEvent($slug) {
        $q = $this->getEntityManager()->createQueryBuilder('e')
             ->select('e.content, e.title')
             ->from('BaseEventBundle:Event', 'e')
             ->where('e.slug = :slug')
             ->setParameter('slug', $slug)
             ->getQuery();

        return $q;
    }

    public function findAllOrderedByUpdatedAt($limit = 5) {
        $query = $this->createQueryBuilder('e')
                      ->addSelect('u.username AS u_username')
                      ->addSelect('m.name AS m_name')
                      ->innerJoin('e.modification_user_id', 'u')
                      ->leftJoin('e.media_id', 'm')
                      ->where('e.is_published = 1')
                      ->orderBy('e.updatedAt', 'DESC')
                      ->setMaxResults($limit)
                      ->getQuery();

        try {
            return $query->getResult($query::HYDRATE_SCALAR);
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }
}

?>
